package com.mazaiting.auth.security.extension.wechat;

import com.mazaiting.auth.constant.SecurityConst;
import com.mazaiting.auth.enums.GrantTypeEnum;
import com.mazaiting.auth.security.extension.base.BaseTokenGranter;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.oauth2.provider.*;
import org.springframework.security.oauth2.provider.token.AbstractTokenGranter;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 微信授权者
 * 声明授权者 WechatTokenGranter 支持授权模式 wechat
 * 根据接口传值 grant_type = wechat_mini_app 的值匹配到此授权者
 * 匹配逻辑详见下面的两个方法
 *
 * @see CompositeTokenGranter#grant(String, TokenRequest)
 * @see AbstractTokenGranter#grant(String, TokenRequest)
 */
public class WechatTokenGranter extends BaseTokenGranter {

    public WechatTokenGranter(AuthorizationServerTokenServices tokenServices, ClientDetailsService clientDetailsService, OAuth2RequestFactory requestFactory, AuthenticationManager authenticationManager) {
        super(tokenServices, clientDetailsService, requestFactory, GrantTypeEnum.WECHAT.getValue(), authenticationManager);
    }

    @Override
    protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) {

        Map<String, String> parameters = new LinkedHashMap<>(tokenRequest.getRequestParameters());
        // 获取 js_code
        String code = parameters.get(SecurityConst.KEY_CODE);
        // 获取加密数据
        String encryptedData = parameters.get(SecurityConst.KEY_ENCRYPTED_DATA);
        // 获取 IV
        String iv = parameters.get(SecurityConst.KEY_IV);

        // 移除后续无用参数
        parameters.remove(SecurityConst.KEY_CODE);
        parameters.remove(SecurityConst.KEY_ENCRYPTED_DATA);
        parameters.remove(SecurityConst.KEY_IV);

        // 未认证状态
        AbstractAuthenticationToken userAuth = new WechatAuthenticationToken(code, encryptedData, iv);
        userAuth.setDetails(parameters);

        return authenticate(client, tokenRequest, userAuth);
    }
}
